<template>
  <div>
    <el-dialog :visible="showStatus" title="编辑数据" :close-on-click-modal="false" @close="showStatus = false">
      <el-form v-if="editingArticle === false" label-width="80px">
        <el-form-item v-for="(item, index) of columns" :key="'column' + index" :label="item.title">
          <div class="flex">
            <!--短文-->
            <el-input v-if="item.type === 'textarea'" v-model="data[item.name]" type="textarea" :autosize="{minRows:3}" />
            <!--文章-->
            <el-button v-else-if="item.type === 'text'" type="default" icon="el-icon-edit" @click="editArticle(item.name)">编辑内容</el-button>
            <!--非文章-->
            <el-input v-else-if="item.type !== 'text'" v-model="data[item.name]" class="flex-1" />
            <!--上传-->
            <el-upload
              v-if="item.type === 'file'"
              ref="upload"
              :action="uploadUrl"
              :auto-upload="true"
              :multiple="false"
              :show-file-list="false"
              style="margin-left: 10px;"
              :on-success="uploadSuccess(item.name)"
            >
              <el-button slot="trigger" type="primary">选择文件</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="showStatus = false">取消</el-button>
          <el-button type="primary" @click="save">提交</el-button>
        </el-form-item>
      </el-form>
      <!--编辑文章-->
      <add-article v-show="editingArticle" ref="article" :on-cancel="cancelArticle" :on-submit="submitArticle" />
    </el-dialog>
  </div>
</template>

<script>
import AddArticle from '@/views/db-data/components/AddArticle'
export default {
  name: 'AddData',
  components: { AddArticle },
  props: {
    onSave: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_UPLOAD_URL,
      showStatus: false,
      columns: [], // [{name: 'age', title: '年龄'}]
      data: {},
      editingArticle: false,
      editingField: ''
    }
  },
  created() {
  },
  methods: {
    open(columns, data) {
      this.columns = columns
      this.data = data
      this.showStatus = true
      this.editingArticle = false
    },
    save() {
      this.showStatus = false
      this.onSave(this.data)
    },
    uploadSuccess(name) {
      return (files) => {
        this.data[name] = files[0]
        this.$forceUpdate()
      }
    },
    editArticle(key) {
      this.editingField = key
      this.editingArticle = true
      const content = typeof this.data[key] !== 'undefined' ? this.data[key] : ''
      this.$refs.article.show(content)
    },
    cancelArticle() {
      this.editingArticle = false
    },
    submitArticle(content) {
      this.editingArticle = false
      this.data[this.editingField] = content
    }
  }
}
</script>

<style scoped lang="scss">

</style>
